<?php

namespace app\modules\prod\controllers;

use yii;
use yii\helpers\Json;
use app\common\Controller;
use app\common\SystemEvent;
use yii\helpers\ArrayHelper;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;
use yii\widgets\ActiveForm;
use yii2mod\editable\EditableAction;
use yii2mod\rbac\filters\AccessControl;
use app\models\Region;
use app\models\RegionType;
use app\models\ProdSpec;
use app\models\ProdInst;
use app\models\Cust;
use app\models\OrderSearch;
use app\models\ProdAttrSpecRela;
use app\models\CustExternalAttr;
use app\models\Order;
use app\models\OrderType;
use app\models\Domain;
use app\models\OrderResumes;
use app\models\Staff;
use app\models\CustomTableView;
use app\models\OrderExternalAttr;
use app\models\UploadForm;
use app\models\Image;
//use kartik\file\FileInput;
use yii\web\UploadedFile;
use app\common\Functions;
use app\models\CustSource;

use yii\data\Pagination;
use yii\data\ActiveDataProvider;
use yii\helpers\Html;

class OrderController extends Controller
{
    
	public $module;
	public $protected_uids = [];    
	public $superadmin_uid = 0;
	public $loginRedirect = '/admin/dashboard';
	public $defaultAction = 'index';
	public function init()
	{
		parent::init();
	}

    /**
     * @name   getParentCustSources
     * @description
     * @param
     * @return
     * @param $cust_source_id
     * @return int
     */
    public function getParentCustSources($cust_source_id )
    {
        $custSource = CustSource::find()->where(['id'=>$cust_source_id])->one();

        if ($custSource)
        {
            return $custSource->parent_source_id;
        }
        return 0;

    }


    /***
     * @name   getCustByAccNbr  根据客户号码取出客户信息
     * @description
     * @param
     * @return 客户模型 包含客户属性
     * @param $tel
     */
    public function getCustByAccNbr($tel)
    {
        $where  = [];


        $where['c.content'] = $tel;
        $where['c.attr_spec_id'] = 3;

        // 先取cust信息，如果有值取继续取最近的一条订单,获得这个号码对应的客户资料
        $query = Cust::find()->alias('a');
        $query->joinWith('custExternalAttrs  AS b');
        $query->joinWith('oneCustExternalAttrs  AS c');
        $query->where($where);
        $model = $query->one();

        return $model;
    }

    /**
     * @name   getCustAttrNbrByOrder 根据订单获取客户属性中的电话号码
     * @description
     * @param
     * @return
     * @param $order_id 订单号
     * @return mixed 客户属性
     */
    public function getCustAttrByOrder($order_id)
    {
        $where  = [];

        $where['a.id'] = $order_id;
        $where['c.attr_spec_id'] = 3;

        $query = Order::find()->alias('a');
        $query->joinWith('custExternalAttrs  AS c');
        $query->where($where);
        $model = $query->one();

        return $model;
    }

    /***
     * @name   getValidOrderByCustID 根据客户编码获取对应的有效订单
     * @description
     * @param
     * @return
     * @param $order_id
     * @return mixed
     */
    public function getValidOrderByCustID($cust_id)
    {
        $where  = [];

        $where['a.object_id'] = $cust_id;
        $where['a.state'] = Yii::$app->params['ORDER_STATE_VALID'];

        $query  = Order::find()->alias('a');
        $query->joinWith('dealUsers  AS e');
        $query->joinWith('externalAttrs  AS o');

        $query->where($where);
        $model = $query->one();
        return $model;
    }

    public function getStaffGroupNameByID($group_id)
    {
        if ($group_id==2)
        {
            return  '业务2部';
        }

        return '业务1部';

    }

    /**01
     * @name           actionRepeatorder
     * @description   排除重复的电话号码,通过号码查询对应的订单信息返回给用户，实际上返回订单和客户的信息，先查询客户，通过客户找到一条订单
     * @param
     * @return
     */
    public function actionRepeatorder($tel=null,$order_id = null)
    {
        $out        = [];
        $results    = [];

        $whereOrder = [];
        $whereByOrderID = [];

        $results['code'] = 0;

        // 使用json返回
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        // 根据号码取出客户信息
        $modelCust = $this->getCustByAccNbr($tel);
        // 如果model有值，则继续取订单信息，状态有效的一条
        if ($modelCust)
        {
            // 如果order_id 有值，则order_id对应的订单获取一下看看是不是同一个号码
            // 这段主要处理update时候的逻辑

            if ($order_id)
            {
                // 取出旧的订单
                $modelOriOrder = $this->getCustAttrByOrder($order_id);
                //
                if ($modelOriOrder)
                {
                    // 如果相同证明还是原来的号码，只是重新输入了一边，直接返回
                    //如果号码冲突 返回4和5，不能随意改变订单对应客户的电话号码
                    if($modelOriOrder->custExternalAttrs->content!=$tel)
                    {
                        $results['code'] = 1; // 没有在途号码重复

                        // 检查客户是否有订单在途
                        $modelOrder = $this->getValidOrderByCustID($modelCust->id);
                        if ($modelOrder)
                        {
                            $results['code'] = 2; // 有在途，不能按照这种方式修改
                            $results["order_region_id"] = $modelOrder->region_id;
                            $results["order_staff_id"]  = $modelOrder->staff_id;
                            $results["order_staff_name"] = $modelOrder->dealUsers->staff_name;
                            $results["order_staff_group"] = $this->getStaffGroupNameByID($modelOrder->dealUsers->staff_group);


                        }

                    }
                }
                $out['results'] = $results;
                return $out;
            }

            $results['code'] = 1;

            // 先为属于cust的属性赋值
            $results["cust_name"]					 		= $modelCust->cust_name;
            $results["cust_source_id"]				    = $modelCust->cust_source_id;

            $results["cust_type_id"]					 	= $modelCust->cust_type_id;
            $results["cust_parentcustsourceid"]		    = $this->getParentCustSources($modelCust->cust_source_id);

            foreach ($modelCust->custExternalAttrs as $custExternalAttrs)
            {
                if ($custExternalAttrs->attr_spec_id==24)
                {
                    $results["cust_localattrsinsts_24_content"] = $custExternalAttrs->content;
                }
                elseif ($custExternalAttrs->attr_spec_id==43)
                {
                    $results["cust_localattrsinsts_43_content"] = $custExternalAttrs->content;
                }
            }

            // 取出客户的有效订单
            $modelOrder = $this->getValidOrderByCustID($modelCust->id);



            if ($modelOrder)
            {
                $results['code'] = 2;
                $results["order_region_id"] = $modelOrder->region_id;
                $results["order_staff_id"]  = $modelOrder->staff_id;
                $results["order_staff_name"] = $modelOrder->dealUsers->staff_name;
                $results["order_staff_group"] = $this->getStaffGroupNameByID($modelOrder->dealUsers->staff_group);


                $results["order_input_time"] = $modelOrder->input_time;

                $results["order_remark"]    = $modelOrder->remark;

                foreach ($modelOrder->externalAttrs as $externalAttrs)
                {
                    switch ($externalAttrs->attr_spec_id)
                    {
                        case 34:
                            $results["order_localattrsinsts_34_content"]	= $externalAttrs->content;
                            break;
                        case 11:
                            $results["order_localattrsinsts_11_content"]	= $externalAttrs->content;
                            $results["order_localattrsinsts_11_content2"]	= $externalAttrs->content2;
                            break;
                        case 23:
                            $results["order_localattrsinsts_23_content"]	= $externalAttrs->content;
                            $results["order_localattrsinsts_23_content2"]	= $externalAttrs->content2;
                            break;
                        case 42:
                            $results["order_localattrsinsts_42_content"]	= $externalAttrs->content;
                            break;
                        case 25:
                            $results["order_localattrsinsts_25_content"]	= $externalAttrs->content;
                            break;
                        case 14:
                            $results["order_localattrsinsts_14_content"]	= $externalAttrs->content;
                            break;
                        case 31:
                            $results["order_localattrsinsts_31_content"]	= $externalAttrs->content;
                            break;
                        case 44:
                            $results["order_localattrsinsts_44_content"]	= $externalAttrs->content;
                            break;
                        default:
                            break;
                    }

                }
            }
        }


        $out['results'] = $results;
        return $out;

//        return $domains->domain_name;
    }

     public function actionIndex($q)
    {
        $query = Region::find();
        $pagination = new Pagination([
            'defaultPageSize' => 5,
            'totalCount' => $query->count(),
        ]);
        $regions = $query->orderBy('region_type_id')->offset($pagination->offset)->limit($pagination->limit)->all();
        return $this->render('index', ['pagination' => $pagination ,
        'regions' => $regions ]);

    }


    public function actionSeachprodinst($q)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];
        if (!$q) {
            return $out;
        }

        $data = ProdInst::find()
            ->select('id, prod_name as text')
            ->where(['prod_spec_id'=>10001])
            ->andFilterWhere(['like', 'prod_name', $q])
            ->limit(12)
            ->asArray()
            ->all();

        $out['results'] = array_values($data);

        return $out;
    }

    public function actionView($id=null, $attr_type_spec_id=null, $prod_spec_name = null)
    {
        $topShowCnt = 0;
        $topShowss = [];

        // 取出标题配置， 是楼盘还是房源 还是其它
        $prodSpecName = $prod_spec_name;

        $model = $this->getOrder($id);

        // 获取到对应图片的全部URL
        $p1 = $this->getAttrInstByID($id );


        //  查询所有该产品的特性值规格，主要用来取名称
        $attrSpecs = $this->getAttrSpecs($attr_type_spec_id);
        $attrSpecNames = [];
        foreach ($attrSpecs as $attrSpec)
        {
            $attrSpecNames[$attrSpec->attrSpecs->attr_spec_id]['name'] = $attrSpec->attrSpecs->attr_spec_name;


        }



        //  获取2级的区域名称
       // $regionList = $this->getParentRegionTypes(0);



        $topShows[$topShowCnt]['field_name']    = '创建用户';
        $topShows[$topShowCnt]['field_values']  = $model->users->username;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '创建时间';
        $topShows[$topShowCnt]['field_values']  = $model->create_date;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '修改用户';
        $topShows[$topShowCnt]['field_values']  = $model->modifyUsers->username;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    =  '修改时间';
        $topShows[$topShowCnt]['field_values']  = $model->modify_date;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    =  '状态';
        $topShows[$topShowCnt]['field_values']  = $model->state;
        $topShowCnt++;


        return $this->render('view',
            ['model' => $model,
                'p1' =>$p1,
                'attrSpecNames' => $attrSpecNames,
                'topShows' => $topShows,
                'attr_type_spec_id' =>$attr_type_spec_id,
                'attrSpecs' => $attrSpecs,
//                'regionList' =>$regionList,
                'prodSpecName' =>$prodSpecName,
                'update'=>1]);
    }

    /*
     *  更新内容
     * */
    public function actionUpdate($id=null, $attr_type_spec_id=null, $prod_spec_name = null)
    {

        // 初始化最重要的产品实例字段
        $postModel   = new Order();

        // 初始化全部的图片
         $uploadModel = new UploadForm();

        // 取出标题配置， 是楼盘还是房源 还是其它
        $prodSpecName = $prod_spec_name;
        //ProdSpec::find()->select(['spec_name'])->where(['id' => $prod_spec_id])->one();

        //取到产品实例数据

  //  $model = $this->findModel($id);
        $model = new Order();

        $query3 = Order::find()->alias('a');

//        $query3->joinWith('regions  AS b');
//        $query3->joinWith('parentRegions  AS c');

        $query3->joinWith('staffs  AS b');

        $query3->joinWith('externalAttrs  AS e');
        $query3->where(['a.id' => $id ]);

        $model2 = $query3->all();

//        Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
//           Yii::trace($model2);

        //  查询所有该产品的特性值
        $attrSpecs = $this->getAttrSpecs($attr_type_spec_id);

        // 构建查询索引，让产品特性实例可以通过类型进行进一步的数据查询
        $attrSpecIndex = [];


        $p1 = $this->getAttrInstByID($id );


        // 先把order取出来
        $fileCnt = 0;
        foreach ($attrSpecs as $attrSpec)
        {
            $attrSpecIndex[$attrSpec->attrSpecs->attr_spec_id]['name']                = $attrSpec->attrSpecs->attr_spec_name;
            $attrSpecIndex[$attrSpec->attrSpecs->attr_spec_id]['attr_spec_type_id'] = $attrSpec->attrSpecs->attr_spec_type_id;
        }
//        Yii::trace("==================");
//        Yii::trace($model2);

        foreach ( $model2 as $prodinst)
        {

            $model->staffName         =  $prodinst->staffs->staff_name;

            $model->id                  = $prodinst->id ;
            $model->order_number      = $prodinst->order_number ;
            $model->object_id          = $prodinst->object_id  ;
            $model->object_type_id    = $prodinst->object_type_id ;
            $model->order_type_id     = $prodinst->order_type_id;
            $model->state              = $prodinst->state;
            $model->staff_id           = $prodinst->staff_id ;
            $model->remark              = $prodinst->remark;

            foreach($prodinst->externalAttrs as $prodAttrInst)
            {
                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['id']                    = $prodAttrInst->id;
                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['content']              = $prodAttrInst->content;
                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['attrSpecTypeID']      = $attrSpecIndex[$prodAttrInst->attr_spec_id]['attr_spec_type_id'];
            }

   
            break;
        }

        //  获取 对应的客户信息


      //   Yii::trace($model);

        if ($postModel->load(Yii::$app->request->post()) && $postModel->validate())
        {
            $postModel->modify_date        = date("Y-m-d H:i:s",time());;
            $postModel->modify_staff_id   = Yii::$app->user->id;

            //更新prod_inst
            $this->insertOrUpdateToTable($postModel, $model);

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            return $this->redirect(['classify','attr_type_spec_id' =>$attr_type_spec_id]);
        }



        //  获取2级的区域名称
        $regionList = $this->getParentRegionTypes(0);

        //$regionList      = $query2->orderBy('id')->all();
        $orderAttrSpecs    = $this->getAttrSpecs(30001);

        // 获取订单类型
        $orderTypes = $this->getOrderTypes();

        return $this->render('update',
            [
                'orderTypes'=>$orderTypes,
                'p1' =>$p1,
                'model' => $model,
                'orderTypes'=>$orderTypes,
                'uploadModel' => $uploadModel,
                'prod_spec_id' =>$attr_type_spec_id,
                'attrSpecs' => $attrSpecs,
                'regionList' =>$regionList,
                'prodSpecName' =>$prodSpecName,
                'update'=>1]);
    }


    public function actionModifyuser($order_id,  $last_url = null)
    {


        // 初始化订单M
        $postModel   = new Order();

//        $query = Order::find()->alias('a');
//        $query->joinWith('users  AS b');

        $order = Order::find()->alias('a')->joinWith('users  AS b')->where(['a.id'=>$order_id])->one();

        $order->staffName         =  $order->staffs->staff_name;


        if ($postModel->load(Yii::$app->request->post()) && $postModel->validate())
        {

            $newState = null;




            //如果没有传入有效的u-id，则默认为转给自己
            if (!$postModel->staff_id){
                $postModel->staff_id = Yii::$app->user->id;
            }

            $this->updateOrder($order_id,$postModel->staff_id, $postModel->remark, 20003 );

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            if ($last_url)
            {
                return $this->redirect($last_url);
            }
            else{

                // 跳回客源抢单页面
                return $this->redirect( ['/prod/order/myorder','object_type_id'=>'1']);
            }
        }

        // 获取状态domain
        // 查询订单状态的种类
        $orderStates = $this->getDomains('order','state');

        if ($order)
        {
            return $this->renderAjax('_modify_uesr_form',
                [
                    'model' => $order,
                    'orderStates' => $orderStates,
                ]);


        }

    }

    // 作废用户
    public function actionCancel($order_id,  $last_url = null)
    {


        //取出个人的用户编码
        $user_id = Yii::$app->user->id;

        // 初始化订单M
        $postModel   = new Order();

        // 根据传入的订单标识找出对应的订单记录
        $order = Order::find()->where(['id'=>$order_id])->one();


        //对反馈的结果进行更新
        if ($postModel->load(Yii::$app->request->post()) && $postModel->validate())
        {

            $postModel->state = 30003;
            $newState = $postModel->state;


            $this->updateOrder($order_id,$user_id, $postModel->remark, 20002, $newState, $postModel->reason);

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            if ($last_url)
            {
                return $this->redirect($last_url);
            }
            else{

                // 跳回客源抢单页面
                return $this->redirect( ['/prod/order/myorder','object_type_id'=>'1']);
            }
        }

        // 获取状态domain
        // 查询订单状态的种类
        $orderStates = $this->getDomains('order','state');

        if ($order)
        {
            return $this->renderAjax('_order_cancel_form',
                [
                    'model' => $order,
                    'orderStates' => $orderStates,
                ]);
        }
    }

    // 信息部作废用户
    public function actionInformation($order_id,  $last_url = null)
    {


        //取出个人的用户编码
        $user_id = Yii::$app->user->id;

        // 初始化订单M
        $postModel   = new Order();

        // 根据传入的订单标识找出对应的订单记录
        $order = Order::find()->where(['id'=>$order_id])->one();


        //对反馈的结果进行更新
        if ($postModel->load(Yii::$app->request->post()) && $postModel->validate())
        {


            $model = Order::find()->where(['id'=>$order_id])->one();
            $model->state_info = 30006;
            $model->remark=$postModel->remark;
            $model->save();



            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            if ($last_url)
            {
                return $this->redirect($last_url);
            }
            else{

                // 跳回客源抢单页面
                return $this->redirect( ['/prod/order/myorder','object_type_id'=>'1']);
            }
        }

        // 获取状态domain
        // 查询订单状态的种类
        $orderStates = $this->getDomains('order','state_info');

        if ($order)
        {
            return $this->renderAjax('_order_cancel_form',
                [
                    'model' => $order,
                    'orderStates' => $orderStates,
                    'info'=>1
                ]);
        }
    }


    //修改日期
    public function actionInputtime($order_id,  $last_url = null){

        //取出个人的用户编码
        $user_id = Yii::$app->user->id;
        $order = Order::find()->where(['id'=>$order_id])->one();

        $model   = new Order();

        // 点击提交时才会执行到这里面
        if ($model->load(Yii::$app->request->post())
            && $model->validate() )
        {
            //	取到form里的数据提交到数据库
            $order->id          = $order_id;
            $order->input_time          = $model->input_time;
            $order->save();

            $orderResumesModel = new OrderResumes();

            $orderResumesModel->order_id           = $order_id;
            $orderResumesModel->staff_id           = $user_id;
            $orderResumesModel->resumes_type_id   = '20008' ;
            $orderResumesModel->create_staff_id   = Yii::$app->user->id;
            $orderResumesModel->create_date        = date("Y-m-d H:i:s",time());
            $orderResumesModel->remark              = $model->remark;
            $orderResumesModel->last_state          = $order->state ;
            $orderResumesModel->next_state          = $order->state;

            $orderResumesModel->save();


            return $this->redirect($last_url);//回到原来页面

        }
        return $this->render('table',[ 'model' => $model]);
    }

    public function getParentProdSpecID($prod_spec_id=null)
    {
        $prodSpec = ProdSpec::find()->select(['parent_prod_spec_id'])->where(['prod_spec_id' => $prod_spec_id])->one();


        return $prodSpec->parent_prod_spec_id;
    }


    // 更新跟进记录
    public function actionHandling($order_id,  $last_url = null)
    {
        if ($order_id)
        {

        }

        //使用自己的身份抢单
        $user_id = Yii::$app->user->id;

        // 初始化订单M
        $postModel   = new Order();
        $prodInstModel = new ProdInst();//和楼相关

        //获取父级产品规格，如果没有返回0
        $parent_prod_spec_id = $this->getParentProdSpecID(10002);


        $order = Order::find()->where(['id'=>$order_id])->one();
        $order_resumes = OrderResumes::find()->where(['order_id'=>$order_id])->orderBy(['id'=> SORT_DESC])->one();


        if ($postModel->load(Yii::$app->request->post()) && $postModel->validate() && $prodInstModel->load(Yii::$app->request->post()) && $prodInstModel->validate() )
        {

            // 检查状态是否有变更
            if ($postModel->state != $order->state)
            {

                $newState = $postModel->state;
            }

            $resumesTypeID = 20004;
            if ($postModel->resumesTypeID)
            {
                $resumesTypeID = $postModel->resumesTypeID;
            }


//            Yii::trace("===================== +++++++++++++++++++++ ============");
//             Yii::trace($prodInstModel->parent_id);
            $parent_id=$prodInstModel->parent_id;


            $this->updateOrder($order_id,$user_id, $postModel->remark, $resumesTypeID,$newState, $postModel->reason,$postModel, false,$parent_id);

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            if ($last_url)
            {
                return $this->redirect($last_url);
            }
            else{

                // 跳回客源抢单页面
                return $this->redirect( ['/prod/order/myorder','object_type_id'=>'1']);
            }


        }

        // 获取状态domain
        // 查询订单状态的种类
        $orderStates = $this->getDomains('order','state');

        if ($order)
        {
            return $this->renderAjax('_handling_resumes_form',
                [
                    'model' => $order,
                    'order_resumes'=>$order_resumes,
                    'orderStates' => $orderStates,
                    'prodInstModel' =>$prodInstModel,
                    'parent_prod_spec_id'=>$parent_prod_spec_id,
                ]);
        }
    }

    public function actionBlacklist($order_id)
    {
        if ($order_id)
        {

        }

        // 初始化订单M
        $postModel   = new Order();

        $order = Order::find()->where(['id'=>$order_id])->one();


        if ($postModel->load(Yii::$app->request->post()) && $postModel->validate())
        {


            $this->updateOrderBlackList($order_id, $postModel->remark);

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            // 跳回客源抢单页面
            return $this->redirect( ['/prod/order/puorder','object_type_id'=>'1']);
        }

        if ($order)
        {
            return $this->renderAjax('_black_list_form',
                [
                    'model' => $order,
                ]);
        }
    }

    public function getAttrSpecs($prod_spec_id)
    {
        $attrSpecRela = ProdAttrSpecRela::find()->alias('f');
        $attrSpecRela->joinWith('attrSpecs  AS g');
        $attrSpecs    = $attrSpecRela->where(['f.prod_spec_id' => $prod_spec_id ])->all();
        return $attrSpecs;
    }

    public function getOrderTypes()
    {
        $orderTypes = OrderType::find()->alias('f')->all();

        return $orderTypes;
    }

    public function getCustSourcesAll()
    {
        $mapCustSource = [];

        $query = CustSource::find()->alias('a');
        $query->joinWith('parentCustSources  AS b');
        $query->orderBy('sort');
        $custSources = $query->all();


        foreach ($custSources as $custSource)
        {
            $mapCustSource[$custSource->id]['name']         = $custSource->cust_source_name;
            $mapCustSource[$custSource->id]['parent_name'] = $custSource->parentCustSources->cust_source_name;
            $mapCustSource[$custSource->id]['show_name'] = $custSource->parentCustSources->cust_source_name  . '-' . $custSource->cust_source_name;
        }

        return $mapCustSource;
    }

    /*
       *  获取订单客户域
       *
       * */
    public function getDomains($domainTableName = null, $domainFieldName = null)
    {
        $where     = []; // 查询条件
        $domainOut = []; //返回的domain数组，以code为索引，name为值的数组
        $where['domain_table_name'] = $domainTableName;
        $where['domain_field_name'] = $domainFieldName;
        $query = Domain::find();
        $domains = $query->where($where)->all();


        foreach ($domains as   $values)
        {
            $domainOut[$values->domain_code ] = $values->domain_name;
        }

        return $domainOut;
    }

    /*       获取房源对应的订单明细
    */
    public function actionProdorder($object_id=null, $order_id = null)
    {


        // 取出所有的订单流水分组
        $sql = "select  a.resumes_type_id,  	a.staff_id,    a.create_staff_id,  a.create_date , DATE_FORMAT( a.create_date ,'%Y-%m-%d') as createDay, a.remark ,";
        $sql .=" c.staff_name , d.staff_name as create_staff_name, a.last_state ,a.next_state from   ";


        $sql .= OrderResumes::tableName();
        $sql .= ' as a Left Join ';
        $sql .= Order::tableName();
        $sql .= ' as b on a.order_id = b.id  Left Join ';
        $sql .= Staff::tableName();
        $sql .= ' as c on  c.user_id = a.staff_id  Left Join ';
        $sql .= Staff::tableName();
        $sql .= ' as d  on  d.user_id = a.create_staff_id  ';


        if ($order_id)
        {
            $sql .= ' where   b.object_id =:object_id  and b.id  =:order_id    order by a.create_date desc  ';
            $orderResumes = Yii::$app->db->createCommand($sql)
                ->bindValue(':object_id', $object_id)
                ->bindValue(':order_id',  $order_id)
                ->queryAll();
        }
        else
        {
            $sql .= ' where   b.object_id =:object_id     order by a.create_date, a.id desc ';
            $orderResumes = Yii::$app->db->createCommand($sql)
                ->bindValue(':object_id', $object_id)
                ->queryAll();
        }



        return $this->renderAjax('time_line', [ 'orderResumes' => $orderResumes]);

    }

    // 无条件查询全部订单
    public function actionAllorder($object_type_id = null, $flag = null)
    {

        $searchModel = new OrderSearch();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams, null, null, $object_type_id );
//        Yii::trace("+++++++++++++++++++++++++++++++++++++++++++++++++++++>");
//        Yii::trace(666);
        return $this->getOrderList(null,null, null,$searchModel,$dataProvider);
    }

    // 查询我处理过的历史订单
    public function actionMinehistory($object_type_id = nul)
    {
        // 取出自己的u_id
        $user_id = Yii::$app->user->id;
        $queryWhere = [];

        $queryWhere['history_order_resumes'] = 'history_order_resumes';
        $queryWhere['staff_id']  = $user_id;
        $queryWhere['state']  = [Yii::$app->params['ORDER_STATE_CANCEL'], Yii::$app->params['ORDER_STATE_OMPLETED']];

        $searchModel = new OrderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,null,null,$object_type_id,null,null,null,null,null, $queryWhere);


        return $this->getOrderList(null,null, $user_id,$searchModel,$dataProvider,null);
    }

    // 查询我创建的订单
    public function actionMinecreate($object_type_id = null, $flag = null)
    {

        // 取出自己的u_id
        $user_id = Yii::$app->user->id;

        $searchModel = new OrderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,null,null,$object_type_id,null,null,$user_id);


        return $this->getOrderList(null,null, $user_id,$searchModel,$dataProvider,null);
    }

    /***
     * @name   actionFollowmanger 主管的成交订单查看
     * @description
     * @param
     * @return
     * @param null $object_type_id
     * @param null $state
     * @return mixed
     */
    public function actionFollowmanger($object_type_id = null, $state = null, $out_time = null ,$time=null)
    {

        // 取出自己的u_id
        $user_id = Yii::$app->user->id;

        //取客户出对应的组
        $staffQuery = Staff::find()->alias('s');
        $staffModel = $staffQuery->where(['s.user_id' => $user_id ])->one();

        //获取自己的分组
        return $this->actionFollow($object_type_id, $state, $staffModel->staff_group,true, $out_time,$staffModel->sub_staff_group ,$time);
    }

    public function actionFollowsupermanger($object_type_id = null, $state = null, $out_time = null ,$time=null)
    {
        $queryWhere = [];

        // 取出自己的u_id
        $user_id = Yii::$app->user->id;

        //取客户出对应的组
        $staffQuery = Staff::find()->alias('s');
        $staffModel = $staffQuery->where(['s.user_id' => $user_id ])->one();

        $staffGroup = 2;
        if ($staffModel)
        {
            $staffGroup = $staffModel->staff_group;
        }

        $queryWhere['staff_group'] = $staffGroup;

        if ($out_time)
        {
            $queryWhere['out_time'] = 3;
        }
        if($_GET['ing']){
            $queryWhere['ing'] = $_GET['ing'];
        }

        $searchModel = new OrderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,null,$state,$object_type_id,null,null,null,$time,null, $queryWhere);


        $encrypted = true;
        return $this->getOrderList(null,null, $user_id,$searchModel,$dataProvider,null,$encrypted,  'order_follow',$staffGroup);
    }

    // 查询业务2部客源跟进中(已成交)
    public function actionFollow($object_type_id = null, $state = null,$staff_group=null,$master=null,  $out_time = null,$sub_staff_group=null ,$time=null)
    {
        $staff_id = null;
        $user_id = null;
        $queryWhere = [];

        if($master || $state=='30001')
        {
            if (!$staff_group) {
                // 取出自己的u_id
                $user_id = Yii::$app->user->id;

                //取客户出对应的组
                $staffQuery = Staff::find()->alias('s');
                $staffModel = $staffQuery->where(['s.user_id' => $user_id])->one();

                $staffGroup = 2;
                if ($staffModel) {
                    $staffGroup = $staffModel->staff_group;
                }
                $queryWhere['staff_group'] = $staffGroup;
            } else {
                $queryWhere['staff_group'] = $staff_group;
            }

            if ($out_time)
            {

                $queryWhere['out_time'] = 3;

                if($master &&$sub_staff_group )
                {
                    $queryWhere['sub_staff_group'] = $sub_staff_group;
                }
                else
                {
                    $staff_id = $user_id;
                }
            }

            $searchModel = new OrderSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams,$staff_id,$state,$object_type_id,null,null,null,$time,null, $queryWhere);
        }
        //
        else
        {
            // 取出自己的u_id
            $user_id = Yii::$app->user->id;
            $searchModel = new OrderSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams,$user_id,$state,$object_type_id,null,null,$time,null,null);

        }




//        $searchModel = new OrderSearch();
//        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,null,$state,$object_type_id,null,null,null,null,null, $queryWhere);

        // 如果是跟进中，用户电话打码
        if ($state=='30001')
        {
            $encrypted = true;
            return $this->getOrderList(null,null, $user_id,$searchModel,$dataProvider,null,$encrypted, 'order_follow', $staff_group);
        }


        return $this->getOrderList(null,null, $user_id,$searchModel,$dataProvider,null,null,  'order_follow_done',$staff_group);
    }


    public function actionFollowmangerSelf($object_type_id = null, $state = null, $out_time = null ,$time=null)//一部
    {


        // 取出自己的u_id
        $user_id = Yii::$app->user->id;

        //取客户出对应的组
        $staffQuery = Staff::find()->alias('s');
        $staffModel = $staffQuery->where(['s.user_id' => $user_id ])->one();

        //获取自己的分组
        return $this->actionFollowSelf($object_type_id, $state, $staffModel->staff_group,true, $out_time,$staffModel->sub_staff_group ,$time);
    }

    public function actionFollowsupermangerSelf($object_type_id = null, $state = null, $out_time = null ,$time=null)//一部
    {
        $queryWhere = [];

        // 取出自己的u_id
        $user_id = Yii::$app->user->id;

        //取客户出对应的组
        $staffQuery = Staff::find()->alias('s');
        $staffModel = $staffQuery->where(['s.user_id' => $user_id ])->one();

        $staffGroup = 2;
        if ($staffModel)
        {
            $staffGroup = $staffModel->staff_group;
        }

        $queryWhere['staff_group'] = $staffGroup;

        if ($out_time)
        {
            $queryWhere['out_time'] = 3;
        }

        $searchModel = new OrderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,null,$state,$object_type_id,null,null,null,$time,null, $queryWhere);


        $encrypted = true;
        return $this->getOrderList(null,null, $user_id,$searchModel,$dataProvider,null,$encrypted,  'order_follow',$staffGroup);
    }

    // 查询业务1部客源跟进中(已成交)
    public function actionFollowSelf($object_type_id = null, $state = null,$staff_group=null,$master=null,  $out_time = null,$sub_staff_group=null ,$time=null)
    {
        $staff_id = null;
        $user_id = null;
        $queryWhere = [];

        if($master || $state=='30001')
        {
            if (!$staff_group) {
                // 取出自己的u_id
                $user_id = Yii::$app->user->id;

                //取客户出对应的组
                $staffQuery = Staff::find()->alias('s');
                $staffModel = $staffQuery->where(['s.user_id' => $user_id])->one();

                $staffGroup = 2;
                if ($staffModel) {
                    $staffGroup = $staffModel->staff_group;
                }
                $queryWhere['staff_group'] = $staffGroup;
            } else {
                $queryWhere['staff_group'] = $staff_group;
            }

            if ($out_time)
            {

                $queryWhere['out_time'] = 3;

                if($master &&$sub_staff_group )
                {
                    $queryWhere['sub_staff_group'] = $sub_staff_group;
                }
                else
                {
                    $staff_id = $user_id;
                }
            }

            $searchModel = new OrderSearch();

            $dataProvider = $searchModel->search(Yii::$app->request->queryParams,$staff_id,$state,$object_type_id,null,null,null,$time,null, $queryWhere);
        }
        //
        else
        {
            // 取出自己的u_id
            $user_id = Yii::$app->user->id;
            $searchModel = new OrderSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams,$user_id,$state,$object_type_id,null,null,$time,null,null);

        }




//        $searchModel = new OrderSearch();
//        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,null,$state,$object_type_id,null,null,null,null,null, $queryWhere);

        // 如果是跟进中，用户电话打码
        if ($state=='30001')
        {
            $encrypted = true;
            return $this->getOrderList(null,null, $user_id,$searchModel,$dataProvider,null,$encrypted, 'order_follow', $staff_group);
        }


        return $this->getOrderList(null,null, $user_id,$searchModel,$dataProvider,null,null,  'order_follow_done',$staff_group);
    }


    //3部的客源查看
    public function actionFollowsupermanger3($object_type_id = null, $state = null, $out_time = null ,$time=null)
    {
        $queryWhere = [];

        // 取出自己的u_id
        $user_id = Yii::$app->user->id;

        //取客户出对应的组
        $staffQuery = Staff::find()->alias('s');
        $staffModel = $staffQuery->where(['s.user_id' => $user_id ])->one();

//        $staffGroup = 2;
        if ($staffModel)
        {
            $staffGroup = $staffModel->staff_group;
        }

        $queryWhere['staff_group'] = $staffGroup;

        if ($out_time)
        {
            $queryWhere['out_time'] = 3;
        }

        $searchModel = new OrderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,null,$state,$object_type_id,null,null,null,$time,null, $queryWhere);


        $encrypted = true;
        return $this->getOrderList(null,null, $user_id,$searchModel,$dataProvider,null,$encrypted,  'order_follow',$staffGroup);
    }




    // 查询我手上的 订单 需要包含我创建的订单
    public function actionMyorders($object_type_id = null, $staff_id = null, $state = null , $flag = null)
    {


        // 取出自己的u_id
        $user_id = Yii::$app->user->id;

        $searchModel = new OrderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams , $staff_id , $state , $object_type_id , null,null,$staff_id);


        return $this->getOrderList(null,null, $user_id,$searchModel,$dataProvider,null ,null,null);
    }

    //查询未分配的订单(无效)
    public function actionPuorder($object_type_id = null, $flag = null)
    {

        $black = 0;
        if ($flag==null)
        {
            $flag='0';
        }


//        // 获取当前的url $last_url
//        $now_url = Yii::$app->request->getUrl();
//
//        $prodSpecName ='订单';

        // 取出自己的u_id
        $user_id = -1;

//        // 获取订单的域
//        $objectTypes = $this->getDomains('order','object_type_id');
//
//        // 查询所有该产品的特性值
//        $attrSpecs    = $this->getAttrSpecs(30001);
//
//        // 查询订单状态的种类
//        $orderStates = $this->getDomains('order','state');
//
//        // 取出区域编码对应的文字
//        $regions = Functions::getRegions();
//
//        $domains = Functions::getAllDomains();

//        Yii::trace("=====================              ============");
//        Yii::trace($regions);


        $searchModel = new OrderSearch();
        switch($flag)
        {
            case 'all':
                $dataProvider = $searchModel->search(Yii::$app->request->queryParams,$user_id,null,$object_type_id);
                break;
            case 'off':// 订单成交
                $dataProvider = $searchModel->search(Yii::$app->request->queryParams,null,'30002',$object_type_id);
                $black=1;
                break;
            case 'black': // 黑名单
                $dataProvider = $searchModel->search(Yii::$app->request->queryParams,$user_id,'30003',$object_type_id, 105);
                $black=1;
                break;
            case 'out': // 订单作废
                $dataProvider = $searchModel->search(Yii::$app->request->queryParams,null,'30003',$object_type_id);
                $black=1;
                break;

            case 'found': //
                $dataProvider = $searchModel->search(Yii::$app->request->queryParams,null,'30003',$object_type_id,null,501);
                $black=1;
                break;



            default:
                $dataProvider = $searchModel->search(Yii::$app->request->queryParams,$user_id,  Yii::$app->params['ORDER_STATE_VALID'],$object_type_id); // 有效的客源订单
                break;

        }
        //$dataProvider = $searchModel->search(Yii::$app->request->queryParams,$user_id,'30001',$object_type_id);

//        $today = date("Y-m-d",time());
//        $regionTodayCnt = Order::find()->where(['AND',['>','modify_date',$today] ])->andWhere(['=','staff_id',$user_id])->count();
//        $regionCnt      = Order::find()->groupBy(['staff_id'])->count();
//
//        $hisTotalOrder = OrderResumes::find()->where(['staff_id'=>$user_id])->count();


        return $this->getOrderList(1,$black, $user_id,$searchModel,$dataProvider);

//        return $this->render('index',
//            [
//                'black'=>$black,
//                'public_flag' => 1,
//                'now_url' => $now_url,
//                'hisTotalOrder' =>  $hisTotalOrder,
//                'domains' => $domains,
//                'objectTypes' => $objectTypes,
//                'orderStates' => $orderStates,
//                'regions' => $regions,
//                'attr_type_spec_id' => 30001,
//                'prodSpecName' =>$prodSpecName,
//                'dataProvider' => $dataProvider,
//                'searchModel' =>  $searchModel,
//                'regionCnt' => $regionCnt,
//                'attrSpecs' => $attrSpecs,
//                'regionTodayCnt' => $regionTodayCnt]);
    }

    /***
     * @name   getOrderList
     * @description
     * @param
     * @return
     * @param null $public_flag
     * @param $black
     * @param int $user_id
     * @param $searchModel
     * @param $dataProvider
     * @param null $times
     * @param null $encrypted
     * @param null $custom_name
     * @param null $authority 如果有权限, 而且权限=sub_group 可以查询小组下的全部内容
     * @return mixed
     */
    public function getOrderList($public_flag=null,$black, $user_id=null,$searchModel,$dataProvider ,$times=null, $encrypted = null, $custom_name = null, $authority = null )
    {
        // 获取当前的url $last_url
        $now_url = Yii::$app->request->getUrl();

        $prodSpecName ='订单';

        // 获取全部的来源名称和对应的父来源名称
        $custSources = $this->getCustSourcesAll();

        // 将$custSources 整理为map
        $custSourceType = [];
        foreach ($custSources as $key => $custSource )
        {
            $custSourceType[$key] = $custSource['show_name'] ;
        }

        // 获取订单的域
        $objectTypes = $this->getDomains('order','object_type_id');

        // 查询所有该产品的特性值
        $attrSpecs    = $this->getAttrSpecs(30001);

        // 查询出对应的展示膜版
        $where = [];
        if ($custom_name )
        {
            $where['a.custom_name'] = $custom_name ;
        }
        else
        {
            $where['a.custom_name'] = 'order';
        }

        $where['a.spec_id'] = 30001;
        $query = CustomTableView::find()->alias('a');
        $customs = $query->where($where)->orderBy('sort ASC')->all();



        // 查询订单状态的种类
        $orderStates = $this->getDomains('order','state');
        $orderStatesd = $this->getDomains('order','state_info');
        $domainSources = $this->getDomains('cust', 'cust_source_id');

        // 去除新增状态
        unset($orderStates[Yii::$app->params['ORDER_STATE_ADD']]);
        $orderStates['']="全部";
//        unset($orderStates[30004]);

        // 取出区域编码对应的文字
        $regions = Functions::getRegions();

        $domains = Functions::getAllDomains();

        $today = date("Y-m-d",time());
        if ($user_id)
        {
            $regionTodayCnt = Order::find()->where(['AND',['>','modify_date',$today] ])->andWhere(['=','staff_id',$user_id])->count();  // 按照区域汇总订单
            $hisTotalOrder = OrderResumes::find()->where(['staff_id'=>$user_id])->count();                                                  // 查询全部属于本人的订单
        }
        else
        {
            $regionTodayCnt = Order::find()->where(['AND',['>','modify_date',$today] ])->count();
            $hisTotalOrder = OrderResumes::find()->count();

        }

        $regionCnt      = Order::find()->groupBy(['staff_id'])->count(); // 全部的订单

        // 获取当前的url $last_url
        $now_url = Yii::$app->request->getUrl();


        $countries=Region::find()->where(['region_type_id'=>4])->all();//地区选择

        $model_d=ArrayHelper::map($countries,'id','region_name');


        $id = Yii::$app->user->id;
        $model_mng=Staff::find()->where(['user_id'=>$id])->one();

        $countries=Staff::find()->where(['staff_group'=>$model_mng->staff_group , 'staff_type_id' => 1])->all();//取出业务x部的人

        $model_staff_name=ArrayHelper::map($countries,'user_id','staff_name');
        $model_staff_name[''] = '全部';
        ksort($model_staff_name);

        //$name=$searchModel->dealUsers->sub_staff_group;
//        $model = $this->getCi

//        Yii::trace("----------------------------------------------------------------------->");
//        Yii::trace($model);
        $orderCounts = [];
        if ($custom_name != 'order_follow_done')
        {
            // 进行数据统计

            // 取出自己的u_id
            $user_id = Yii::$app->user->id;

            //  $orderCounts['monthOrderCount']        = $this->getMonthOrderCount();            // 获取本月的订单总数


            $searchMonthOrderCountModel     = new OrderSearch();
            $searchWeekOrderCountModel      = new OrderSearch();
            $searchDayOrderCountModel       = new OrderSearch();
            $searchOutOrderCountModel       = new OrderSearch();
            $searchLiveMonthOrderCountModel = new OrderSearch();
            $searchLiveWeekOrderCountModel  = new OrderSearch();
            $searchDayOrderCountsModel      = new OrderSearch();



            $monthOrderSql['whereLeft']     = "date_format(a.input_time,'%Y-%m')";
            $weekOrderSql['whereLeft']      = "YEARWEEK(date_format(a.input_time,'%Y-%m-%d'))";
            $dayOrderSql['whereLeft']       = "date_format(a.input_time,'%Y-%m-%d')";
            $outOrderSql['whereLeft']       = "a.modify_date";
            $liveMonthOrderSql['whereLeft'] = "date_format(a.modify_date,'%Y-%m')";
            $liveWeekOrderSql['whereLeft']  = "YEARWEEK(date_format(a.modify_date,'%Y-%m-%d'))";
            $dayOrdersSql['whereLeft']      = "date_format(a.modify_date,'%Y-%m-%d')";

            $day=Functions::getWeekend();//周末剔除
            $monthOrderSql['whereRight']     = "date_format(now(),'%Y-%m')";
            $weekOrderSql['whereRight']      = "YEARWEEK(now())";
            $dayOrderSql['whereRight']       = "date_format(now(),'%Y-%m-%d')";
            $outOrderSql['whereRight']       = "DATE_SUB(now(),INTERVAL 4+".$day." DAY)";
            $liveMonthOrderSql['whereRight'] = "date_format(now(),'%Y-%m')";
            $liveWeekOrderSql['whereRight']  = "YEARWEEK(now())";
            $dayOrdersSql['whereRight']      = "date_format(now(),'%Y-%m-%d')";

            $monthOrderSql['whereMidle']     =   '=';
            $weekOrderSql['whereMidle']      =   '=';
            $dayOrderSql['whereMidle']       =   '=';
            $outOrderSql['whereMidle']       =   '<';
            $liveMonthOrderSql['whereMidle'] =   '=';
            $liveWeekOrderSql['whereMidle']  =   '=';
            $dayOrdersSql['whereMidle']      =   '=';


            $outOrderSql['whereState']       =   Yii::$app->params['ORDER_STATE_VALID'];
            $liveMonthOrderSql['whereState'] =   Yii::$app->params['ORDER_STATE_VALID'];
            $liveWeekOrderSql['whereState']  =   Yii::$app->params['ORDER_STATE_VALID'];
            $dayOrdersSql['whereState']      =   Yii::$app->params['ORDER_STATE_VALID'];

            //如果是部门跟进中不带自己的$user_id
            if ( $encrypted )
            {
                $query_staff_id = null;
            }
            else
            {
                $query_staff_id = $user_id;
            }

            $orderCounts['monthOrderCount']        = $searchMonthOrderCountModel->getMonthOrderCount($query_staff_id,$monthOrderSql);            //本月订单数
            $orderCounts['weekOrderCount']         = $searchWeekOrderCountModel->getMonthOrderCount($query_staff_id,$weekOrderSql);             // 获取本周的订单总数
            $orderCounts['dayOrderCount']          = $searchDayOrderCountModel->getMonthOrderCount($query_staff_id,$dayOrderSql);              // 本日新增
            $orderCounts['outOrderCount']          = $searchOutOrderCountModel->getMonthOrderCount($query_staff_id,$outOrderSql,3);              // 3日未反馈
            $orderCounts['liveMonthOrderCount']   = $searchLiveMonthOrderCountModel->getMonthOrderCount($query_staff_id,$liveMonthOrderSql,3);        // 本月有效
            $orderCounts['liveWeekOrderCount']    = $searchLiveWeekOrderCountModel->getMonthOrderCount($query_staff_id,$liveWeekOrderSql);          // 本周分配
            $orderCounts['dayOrderCounts']         = $searchDayOrderCountsModel->getMonthOrderCount($query_staff_id,$dayOrdersSql);             //本日分配

        }





//一部
        $orderCounts['monthOrderCount1']        = $this->getMonthOrderCount1(30001);
        $orderCounts['monthOrderCountOk']        = $this->getMonthOrderCount1(30002);
        $orderCounts['weekOrderCount1']         = $this->getWeekOrderCount();             // 获取本周的订单总数
//        $orderCounts['dayOrderCount']          = $this->getDayOrderCount();              // 本日新增
        $orderCounts['outOrderCount1']          = $this->getOutOrderCount();              // 3日未反馈
//        $orderCounts['liveMonthOrderCount']   = $this->getLiveMonthOrderCount();        // 本月有效
//        $orderCounts['liveWeekOrderCount']    = $this->getLiveWeekOrderCount();          // 本周分配
//        $orderCounts['dayOrderCounts']          = $this->getDayOrderCounts();             //本日分配

        $myid=Functions::getMyid();//区分1，2部

        return $this->render('index',
            [
                'myid'=>$myid,
                'authority'=>$authority,
                'encrypted'=>$encrypted,
                'times'=>$times,
                'model_staff_name'=>$model_staff_name,
                'orderCounts'=>$orderCounts,
                'custSourceType'=>$custSourceType,
                'custSources'=>$custSources,
                'domainSources'=>$domainSources,
                'customs'=>$customs,
                'black'=>$black,
                'public_flag' => $public_flag,
                'now_url' => $now_url,
                'hisTotalOrder' =>  $hisTotalOrder,
                'domains' => $domains,
                'objectTypes' => $objectTypes,
                'orderStates' => $orderStates,
                'orderStatesd'=>$orderStatesd,
                'regions' => $regions,
                'attr_type_spec_id' => 30001,
                'prodSpecName' =>$prodSpecName,
                'dataProvider' => $dataProvider,
                'searchModel' =>  $searchModel,
                'regionCnt' => $regionCnt,
                'attrSpecs' => $attrSpecs,
                'model_d' => $model_d,
                'model_mng'=>$model_mng,
                'regionTodayCnt' => $regionTodayCnt]);
    }

    // 获取本月的订单总数
    public function getMonthOrderCount()
    {
        //Yii::$app->request->queryParams;

        $sql  = "SELECT count(*) as OrderCount FROM ";
        $sql .=  Order::tableName();
        $sql .= "  where date_format(input_time,'%Y-%m')=date_format(now(),'%Y-%m')  and order_type_id=:order_type_id ";
        $query = Yii::$app->db->createCommand($sql);
        $query->bindValue(':order_type_id', '1') ;
        $monthOrderCount = $query->queryOne();
//        $monthOrderCount = Yii::$app->db->createCommand($sql)
//            ->bindValue(':order_type_id', '1')
//            ->queryOne();

        return $monthOrderCount['OrderCount'];
    }

    // 获取本月的订单总数（1部头部信息）
    public function getMonthOrderCount1($state)
    {

        $sql  = "SELECT count(*) as OrderCount FROM ";
        $sql .=  Order::tableName();
        $sql .= " as a LEFT JOIN";
        $sql .=  Staff::tableName();
        $sql .= " as e ON a.staff_id = e.user_id";
        $sql .= "  where e.staff_group=:staff_group   and date_format(a.modify_date,'%Y-%m')=date_format(now(),'%Y-%m')  and a.order_type_id=:order_type_id  and a.state = :state";
        $query = Yii::$app->db->createCommand($sql)
                ->bindValue(':staff_group', '1')
                ->bindValue(':order_type_id', '1')
                ->bindValue(':state', $state) ;
        $monthOrderCount = $query->queryOne();

        return $monthOrderCount['OrderCount'];
    }


    // 获取本周的订单总数
    public function getWeekOrderCount()
    {


        $sql  = "SELECT count(*)  as OrderCount FROM ";
        $sql .=  Order::tableName();
        $sql .= " as a LEFT JOIN";
        $sql .=  Staff::tableName();
        $sql .= " as e ON a.staff_id = e.user_id";
        $sql .= "  WHERE  e.staff_group=:staff_group   and YEARWEEK(date_format( a.modify_date,'%Y-%m-%d')) = YEARWEEK(now()) and a.order_type_id=:order_type_id ";

        $weekOrderCount = Yii::$app->db->createCommand($sql)
            ->bindValue(':staff_group', '1')
            ->bindValue(':order_type_id', '1')
            ->queryOne();
        return $weekOrderCount['OrderCount'];
    }

    // 本日新增
    public function getDayOrderCount()
    {
        $sql  = "SELECT count(*)  as OrderCount FROM ";
        $sql .=  Order::tableName();
        $sql .= "  where date_format(input_time,'%Y-%m-%d')=date_format(now(),'%Y-%m-%d')  and order_type_id=:order_type_id ";

        $dayOrderCount = Yii::$app->db->createCommand($sql)
            ->bindValue(':order_type_id', '1')
            ->queryOne();

        return $dayOrderCount['OrderCount'];
    }

    // 3日未反馈
    public function getOutOrderCount()
    {

        $day=Functions::getWeekend();

        $sql  = "SELECT count(*) as OrderCount FROM ";
        $sql .=  Order::tableName();
        $sql .= " as a LEFT JOIN";
        $sql .=  Staff::tableName();
        $sql .= " as e ON a.staff_id = e.user_id";
        $sql .= "  where e.staff_group=:staff_group  and a.modify_date<DATE_SUB(now(),INTERVAL :day DAY)   and a.order_type_id=:order_type_id and a.state = :state";

        $outOrderCount = Yii::$app->db->createCommand($sql)
            ->bindValue(':day', 4+$day)
            ->bindValue(':staff_group', '1')
            ->bindValue(':order_type_id', '1')
            ->bindValue(':state',  30001)
            ->queryOne();

        return $outOrderCount['OrderCount'];
    }

    // 本月跟进中
    public function getLiveMonthOrderCount()
    {
        $sql  = "SELECT count(*)  as OrderCount FROM ";
        $sql .=  Order::tableName();
        $sql .= "  where date_format(input_time,'%Y-%m')=date_format(now(),'%Y-%m')  and order_type_id=:order_type_id and state = :state ";

        $liveMonthOrderCount = Yii::$app->db->createCommand($sql)
            ->bindValue(':order_type_id', '1')
            ->bindValue(':state',  Yii::$app->params['ORDER_STATE_VALID'])
            ->queryOne();

        return $liveMonthOrderCount['OrderCount'];
    }


    // 本周分配
    public function getLiveWeekOrderCount()
    {
        $sql  = "SELECT count(*)  as OrderCount FROM ";
        $sql .=  Order::tableName();
        $sql .= "  WHERE YEARWEEK(date_format(input_time,'%Y-%m-%d')) = YEARWEEK(now()) and order_type_id=:order_type_id  and state = :state ";
      //  $sql .= "  where date_format(input_time,'%Y-%m')=date_format(now(),'%Y-%m')  and order_type_id=:order_type_id and state = :state ";

        $liveWeekOrderCount = Yii::$app->db->createCommand($sql)
            ->bindValue(':order_type_id', '1')
            ->bindValue(':state',  Yii::$app->params['ORDER_STATE_VALID'])
            ->queryOne();

        return $liveWeekOrderCount['OrderCount'];
    }

    // 本日分配
    public function getDayOrderCounts()
    {
        $sql  = "SELECT count(*)  as OrderCount FROM ";
        $sql .=  Order::tableName();
        $sql .= "  where date_format(input_time,'%Y-%m-%d')=date_format(now(),'%Y-%m-%d')  and order_type_id=:order_type_id ";

        $dayOrderCount = Yii::$app->db->createCommand($sql)
            ->bindValue(':order_type_id', '1')
            ->queryOne();

        return $dayOrderCount['OrderCount'];
    }



        //查询我的订单
    public function actionMyorder($object_type_id = null ,$times=null)
    {
        $black = 0;
//        $prodSpecName ='订单';

        // 取出自己的u_id
        $user_id = Yii::$app->user->id;

//        // 获取订单的域
//        $objectTypes = $this->getDomains('order','object_type_id');
//
//        // 查询所有该产品的特性值
//        $attrSpecs    = $this->getAttrSpecs(30001);
        $time=$_GET['time'];

        if($_GET['phone']){
            $phone=$_GET['phone'];//手机号
            $query = CustExternalAttr::find()->alias('a');
            $query->where(['a.attr_spec_id' => 3 , 'a.content' => $phone]);
            $model = $query->one();
            $phone=$model->cust_id;
        }


        $searchModel = new OrderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,$user_id,'30001',$object_type_id,null,null,null,$time,$phone);

//        $today = date("Y-m-d",time());
//        $regionTodayCnt = Order::find()->where(['AND',['>','modify_date',$today] ])->andWhere(['=','staff_id',$user_id])->count();
//        $regionCnt      = Order::find()->groupBy(['staff_id'])->count();

        return $this->getOrderList(null,$black, $user_id, $searchModel, $dataProvider ,$times);


    }


    /*
     * @p prod_spec_id 产品规格
     *
     * */
    public function actionClassify($attr_type_spec_id=null)
    {

        // 获取订单的域
        $objectTypes = $this->getDomains('order','object_type_id');

        // 取出标题配置， 是楼盘还是房源 还是其它
       // $prodSpec = ProdSpec::find()->select(['spec_name'])->where(['prod_spec_id' => $prod_spec_id])->one();
        $prodSpecName ='订单';

        // 查询所有该产品的特性值
        $attrSpecs    = $this->getAttrSpecs($attr_type_spec_id);


        // 取出区域编码对应的文字
       // $regionTypes = $this->getRegionTypes();



        $searchModel = new OrderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);



        $today = date("Y-m-d",time());
        $regionTodayCnt = Order::find()->where(['AND',['>','modify_date',$today] ])->count();
        $regionCnt      = Order::find()->groupBy(['staff_id'])->count();



        return $this->render('classify',
            [
                'objectTypes' => $objectTypes,
                'attr_type_spec_id' => $attr_type_spec_id,
                'prodSpecName' =>$prodSpecName,
//                'regionTypes' => $regionTypes,
                'dataProvider' => $dataProvider,
                'searchModel' =>  $searchModel,
                'regionCnt' => $regionCnt,
                'attrSpecs' => $attrSpecs,
                'regionTodayCnt' => $regionTodayCnt]);

    }

    // 创建子集
    //public function actionCreateSub($region_type_id=null,$region_type_name=null)

    public function actionCreate($attr_type_spec_id=null, $parent_prod_id = null, $cust_id=null, $prod_id=null)
    {

        // 初始化类型
        $model = new Order();

        if ($model->load(Yii::$app->request->post()) && $model->validate())
        {
//            Yii::trace("=====================              ============");
//            Yii::trace($model);
//            Yii::trace($model->parent_id);


           // $model->parent_region_id  = 0;
            $model->staff_id           = Yii::$app->user->id;
            $model->create_date        = date("Y-m-d H:i:s",time());;
            $model->create_staff_id   = Yii::$app->user->id;
            $model->modify_date        = date("Y-m-d H:i:s",time());;
            $model->modify_staff_id   = Yii::$app->user->id;
            $model->state               = 'ON';

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            //创建Region
            $this->insertOrUpdateToTable($model);
            return $this->redirect(['classify','attr_type_spec_id' =>$attr_type_spec_id]);

        }

        // 获取订单类型
        $orderTypes = $this->getOrderTypes();

        // 如果是从客户端过来的订单，需要默认对象类型和ID
        if ($cust_id)
        {
            $model->object_id = $cust_id;
            $model->object_type_id = 1;
        }
        else
        {
            $model->object_id = $prod_id;
            $model->object_type_id = 2;
        }

        // 查询所有该产品的特性规格
        $attrSpecs    = $this->getAttrSpecs($attr_type_spec_id);

        // 父区域编码
        $parent_region_id = 0;

        $regionList      = $this->getParentRegionTypes($parent_region_id);


        $p1 = [];

        // 初始化全部的图片
        $uploadModel = new UploadForm();

        return $this->render('create',
                            [
                                'orderTypes' => $orderTypes,
                                'parent_prod_id' => $parent_prod_id,
                                'cust_id' =>$cust_id,
                                'prod_id' =>$prod_id,
                                'p1' =>$p1,
                                'model' => $model,
                                'uploadModel' => $uploadModel,
                                'attr_type_spec_id' =>$attr_type_spec_id,
                                'attrSpecs' => $attrSpecs,
                                'regionList' =>$regionList]);


    }


    public function actionSite($parent_region_id=null)
    {
        $query = new Region();
        $model = $query->getCityList($parent_region_id);

        echo Html::tag('option','选择区域', ['value'=>'empty']) ;
        foreach($model as $value=>$name)
        {
            echo Html::tag('option',Html::encode($name),array('value'=>$value));
        }
    }

    // 抢单
    public function actionGrab($id=null)
    {
        $whereOrder = [];

        //使用自己的身份抢单
        $user_id = Yii::$app->user->id;

        // 查询自己的额度和待处理的订单
        // 根据查出来的id找到员工额度
        $staff = Staff::find()->where(['user_id'=>$user_id ])->one();



        // 根据处理人找出自己正在处理中的订单
        $whereOrder['staff_id'] = $user_id;                                         // 处理人为自己
        $whereOrder['state']     = Yii::$app->params['ORDER_STATE_VALID'];      // 订单状态有效
        $dealOredrCnt = Order::find()->where($whereOrder)->count();

        // 如果额度小于等于正在处理中的订单，直接返回抢单失败，提示额度不足
        if ($staff->cust_limit<=$dealOredrCnt)
        {
            Yii::$app->session->setFlash('error', Yii::t('region', '订单处理的额度已经满了，请联系主管增加额度，您的额度是：' . $staff->cust_limit ));

            // 跳回客源抢单页面
            return $this->redirect( ['/prod/order/puorder','object_type_id'=>'1']);

        }


        try
        {
            $this->updateOrder($id, $user_id, "公盘抢单",20006);
            // Yii::$app->getAuthManager()->remove($model->item);
            Yii::$app->session->setFlash('success', Yii::t('region', '抢单成功.'));
        }
        catch (IntegrityException $e){
            Yii::$app->session->setFlash('success', Yii::t('region', '抢单失败.'));
            //  return $this->redirect(Yii::$app->request->getReferrer());
        }

        // 跳回客源抢单页面
        return $this->redirect( ['/prod/order/puorder','object_type_id'=>'1']);
    }

    public function updateOrder($id, $user_id, $remark=null,$resumes_type_id=null, $newState=null,$reason=null,$postModel=null, $modifySatff=true ,$parent_id=null)
    {
        $order = Order::find()->where(['id'=>$id])->one();
//        Yii::trace("=============newState==================");
//        Yii::trace($newState);

        $oldState = $order->state;
        if($order)
        {
            if ($newState)
            {
                $order->state = $newState;
            }
            //如果撤单原因有值且状态变更为无效
            if ($reason && $order->state==30003)
            {
                $order->reason = $reason;
            }
            //$order->remark  =  $remark;
            if($modifySatff){

                $order->staff_id           = $user_id;
            }





            $order->modify_date        = date("Y-m-d H:i:s",time());;
            $order->modify_staff_id   = Yii::$app->user->id;
          //  $order->remark              = $remark;
            $order->save();




            $orderResumesModel = new OrderResumes();

            $orderResumesModel->order_id           = $id;
            $orderResumesModel->staff_id           = $user_id;
            $orderResumesModel->resumes_type_id   = $resumes_type_id ;
            $orderResumesModel->create_staff_id   = Yii::$app->user->id;
            $orderResumesModel->create_date        = date("Y-m-d H:i:s",time());
            $orderResumesModel->remark              = $remark;
            $orderResumesModel->last_state          = $oldState ;
            $orderResumesModel->next_state          = $order->state;
            $orderResumesModel->peculiarity          = $parent_id;//房源对应的ID
            $orderResumesModel->save();
        }





    }

    //恢复信息状态
    public function actionUpdates(){
        $id=$_GET['order_id'];
        $order = Order::find()->where(['id'=>$id])->one();
        $order->state_info=           30005;
        $order->save();

        return $this->redirect( ['/prod/order/allorder','object_type_id'=>'1']);
    }

    //订单不存在删除 只有作废
    public function actionDelete($id, $attr_spec_type_id=null)
    {

        try{
            $this->deleteOrder($id);
           // Yii::$app->getAuthManager()->remove($model->item);
            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));
        }catch (IntegrityException $e){
            Yii::$app->session->setFlash('success', Yii::t('region', '删除失败.'));
          //  return $this->redirect(Yii::$app->request->getReferrer());
        }

        return $this->redirect(['classify','attr_spec_type_id' => $attr_spec_type_id]);
    }

    public function deleteOrder($id)
    {

        // 删除订单属性实例
//        $order = Order::find()->where(['id'=>$id])->one();

        // 删除订单本体
        $order = Order::find()->where(['id'=>$id])->one();
        if($order)$order->delete();


    }


    /*通过prod-id获取全部的产品属性实例*/
    public function  getAttrInstByID($id=null )
    {

        $model=[];
        $query = CustExternalAttr::find()->alias('a');
        $query->joinWith('attrSpecs  AS b');
        $query->joinWith('images  AS c');


        $query->where(['a.cust_id' => $id , 'b.attr_spec_type_id' => 2]);
        $models = $query->all();

        foreach ($models as $key => $values)
        {
            $model[$values->attrSpecs['attr_spec_id']][] = $values->images['url'] . $values->images['image_name'];
        }

        return $model;
    }

    /*通过prod-id获取全部的产品实例*/
    public function getOrder($id=null)
    {
        // 初始化最重要的产品实例字段
        $model = new Cust();


        $query = Order::find()->alias('a');
        $query->joinWith('users  AS f');
        $query->joinWith('modifyUsers  AS g');
        $query->joinWith('regions  AS b');
        $query->joinWith('parentRegions  AS c');
        $query->joinWith('custExternalAttrs  AS e');
        $query->where(['a.id' => $id ]);
        $models = $query->all();

        $model = $models[0];
        foreach($models[0]->custExternalAttrs as $attrSpec)
        {
            $model->attrSpecs[$attrSpec->attr_spec_id] = $attrSpec->content;
        }


        return $model;
    }

    // 取出父级区域编码对应的文字
    public function getParentRegionTypes($parent_region_id)
    {
        $query2 = Region::find();
        $query2->where(['parent_region_id' => $parent_region_id ]);
        $regionList      = $query2->orderBy('id')->all();
        return $regionList;
    }

    // 取出区域编码对应的文字
    public function getRegionTypes()
    {

        $regionTypes = [];
        $query = RegionType::find()->alias('a');
        $queryRegionTypes = $query->all();
        foreach ($queryRegionTypes as $queryRegionType)
        {
            $regionTypes[$queryRegionType->id] = $queryRegionType->region_type_name;
        }

        return $regionTypes;
    }


    public function saveFile($file)
    {
        $url = 'uploads/';
        $filelName =  time().rand(100,999) . '.' . $file->extension;
        $file->saveAs($url . $filelName);

        // 将图片地址存入数据库，记录该图片的来源时间和上传人
        $image                = new Image();
        $image->image_name  = $filelName;
        $image->url          = '/' . $url;
        $image->create_date = date("Y-m-d H:i:s",time());
        $image->staff_id     = Yii::$app->user->id;

        $image->save();

        // 获得id
        $imageId = $image->attributes['id'];

        return $imageId;
    }
    /**
     * 新增或者修改 role table
     * @param $newRole
     * @param string $oldRole
     */
    public function insertOrUpdateToTable( $newModel, $oldModel=null)
    {
        $i = 0;                       // 批量插入的数量
        $resumes_type_id = 20004;     // 默认为修改描述
        $insertOrderResumes =[];      // 批量插入的数组
        //$oldAttrInst = [];  // 旧的产品特性实例
        // 'order_id','resumes_type_id','last_state','next_state','remark','staff_id', create_staff_id
        if($oldModel)
        {
            $model = Order::find()->where(['id'=>$newModel->id])->one();

            // 如果没有选分配处理人,使用公盘当做是处理人
            if ($newModel->staff_id=null)
            {
                $newModel->staff_id = -1;
            }

            //

            // 计算日志如何插入
            // 如果员工发生了变化为修改负责人
            if ($model->staff_id!= $newModel->staff_id)
            {
                $resumes_type_id = 20003;
                // 增加备注 这个是百分百有的
                $insertOrderResumes[$i][] = $newModel->id;
                $insertOrderResumes[$i][] = $resumes_type_id;
                $insertOrderResumes[$i][] = $model->state;
                $insertOrderResumes[$i][] = $model->state_info;
                $insertOrderResumes[$i][] = $newModel->state;
                $insertOrderResumes[$i][] = $newModel->remark;
                $insertOrderResumes[$i][] = $newModel->staff_id;
                $insertOrderResumes[$i][] = Yii::$app->user->id;;
                $i++;
            }

            // 状态变更
            if ($model->state!= $newModel->state)
            {
                $resumes_type_id = 20005;
                // 增加备注 这个是百分百有的
                $insertOrderResumes[$i][] = $newModel->id;
                $insertOrderResumes[$i][] = $resumes_type_id;
                $insertOrderResumes[$i][] = $model->state;
                $insertOrderResumes[$i][] = $model->state_info;
                $insertOrderResumes[$i][] = $newModel->state;
                $insertOrderResumes[$i][] = $newModel->remark;
                $insertOrderResumes[$i][] = $newModel->staff_id;
                $insertOrderResumes[$i][] = Yii::$app->user->id;;
                $i++;
            }

            // 订单结束
            $model->modify_date        = date("Y-m-d H:i:s",time());;
            $model->modify_staff_id   = Yii::$app->user->id;

            $model->state               = $newModel->state ;
            $model->remark              = $newModel->remark  ;
            $model->staff_id           = $newModel->staff_id  ;

            $model->save();

            //

        }
        else
        {
            // 如果没有选分配处理人,使用创建人当做是处理人
            if ($newModel->staff_id=null)
            {
                $newModel->staff_id = Yii::$app->user->id;
            }
            $newModel->save();

            // 获得id
            $id = $newModel->attributes['id'];


        }

        // 如果插入数组不为空则执行插入
//        if (!empty($insertModelAttrs))
//        {
//            Yii::$app->db->createCommand()->batchInsert(CustExternalAttr::tableName(), ['cust_id','attr_spec_id','content','sort'], $insertModelAttrs)->execute();
//        }
        if (!empty($insertOrderResumes))
         {
             Yii::$app->db->createCommand()->batchInsert(OrderResumes::tableName(), ['order_id','resumes_type_id','last_state','next_state','remark','staff_id','create_staff_id'], $insertOrderResumes)->execute();
         }


    }

//    public function actionIndex()
//    {
//        $menus = SystemEvent::GetAdminMenu();
//        if(Yii::$app->request->isAjax){
//            return '<script>OA_Menus='.Json::encode($menus).'</script>';
//        }
//        return $this->renderPartial('index',['menus'=>$menus]);
//    }

//客服的回访订单表
    public function actionReturn($object_type_id = null, $flag = null)
    {

        $sql  = "SELECT  c.cust_name As name,";
        $sql .= "o3.content As cell,";
        $sql .="cs2.cust_source_name As inf,";
        $sql .="cs.cust_source_name As source ,";
        $sql .="dm44.domain_name As conm,";
        $sql .="r.region_name As yx,";
        $sql .=" dm24.domain_name As industry,";
        $sql .="s2.staff_name As attract,";
        $sql .=" s.staff_name As keyboarder,";
        $sql .=" o.create_date As time ,";
        $sql .=" COUNT(`b`.`order_id`) As sum ,";
        $sql .=" b.remark As remark  FROM";
        $sql .= Order::tableName();
        $sql .= " as o  LEFT JOIN";
        $sql .= Staff::tableName() ;
        $sql .= " as s on o.create_staff_id = s.user_id";
        $sql .= " LEFT JOIN ";
        $sql .= Staff::tableName() ;
        $sql .= " as s2 on o.modify_staff_id = s2.user_id";
        $sql .= " LEFT JOIN ";
        $sql .= Region::tableName() ;
        $sql .= " as r on o.region_id = r.id";
        $sql .= " LEFT JOIN ";
        $sql .= CustExternalAttr::tableName() ;
        $sql .= " as o3 on o.object_id = o3.cust_id  and o3.attr_spec_id = 3";
        $sql .= " LEFT JOIN ";
        $sql .= Cust::tableName() ;
        $sql .= " as c on o.object_id = c.id";
        $sql .= " LEFT JOIN ";
        $sql .= CustSource::tableName() ;
        $sql .= " as cs on cs.id  = c.cust_source_id";
        $sql .= " LEFT JOIN ";
        $sql .= CustSource::tableName() ;
        $sql .= " as cs2 on cs2.id  = cs.parent_source_id";
        $sql .= " LEFT JOIN ";

        $sql .= CustExternalAttr::tableName() ;
        $sql .= " as o24 on o.object_id = o24.cust_id  and o24.attr_spec_id = 24";
        $sql .= " LEFT JOIN ";
        $sql .= Domain::tableName() ;
        $sql .= " as dm24 on dm24.domain_code = o24.content";
        $sql .= " LEFT JOIN ";
        $sql .= OrderExternalAttr::tableName() ;
        $sql .= " as o44 on  o.id = o44.order_id   and o44.attr_spec_id = 44";
        $sql .= " LEFT JOIN ";
        $sql .= Domain::tableName() ;
        $sql .= " as dm44 on dm44.domain_code = o44.content";
        $sql .= " LEFT JOIN ";
        $sql .= OrderResumes::tableName() ;
        $sql .= " as  `b` ON `o`.`id` = `b`.`order_id`";
//        $sql .=  " WHERE  o.object_type_id = 1 and o.create_date between  date_format(:b_create_date, '%Y%m%d%H%i%s') and  date_format(:e_create_date, '%Y%m%d%H%i%s') order by o.id desc ";
        $sql .=  " WHERE  o.object_type_id = :b and   b.`resumes_type_id` IN(20010 ,20012, 20013,20015) group by `b`.`order_id` order by o.id desc ";


        $lendedAreas = Yii::$app->db->createCommand($sql)
            ->bindValue(':b',1 )
            ->query();


//        $pagination = new Pagination([//new Pagination定义分页
//            'defaultPageSize' => 50,//每页50条
//            'totalCount' => $lendedAreas->count(),//总数
//        ]);
//        $regions = $lendedAreas->offset($pagination->offset)->limit($pagination->limit)->all();

        return $this->render('view2',
            [
                'regions' => $lendedAreas ]);

    }

}

